package org.ceva.training.controller;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

import org.ceva.training.persistence.bo.User;
import org.ceva.training.persistence.dao.UsersDAO;
import org.ceva.training.service.Credentials;

public class LogonFormController extends SimpleFormController {
	private int sessionTimeOut;
	
	public ModelAndView onSubmit(Object command) throws ServletException {
		return new ModelAndView(new RedirectView(getSuccessView()));
	}

	
	public int getSessionTimeOut() {
		return sessionTimeOut;
	}

	public void setSessionTimeOut(int sessionTimeOut) {
		this.sessionTimeOut = sessionTimeOut;
	}

	
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException error)
			throws Exception {
		return super.onSubmit(request, response, command, error);

	}
	
	public final String getText(final String msgKey) {
	    return getMessageSourceAccessor().getMessage(msgKey);
	}

	
	protected void onBindAndValidate(HttpServletRequest request, Object object,
			BindException errors) throws Exception {
		
		logger.info("OnBind Validator Called");
		Credentials credentials = (Credentials) object;
		logger.info("Calling Validator");
		String userpwd = null;
		String username = null;
		if (credentials == null) {
			errors.rejectValue("username", "error.login.not-specified", null,"Value required.");
		} else {
			logger.info("Validating user credentials for: " + credentials.getUsername());
			UsersDAO userDAO = (UsersDAO) this.getApplicationContext().getBean("UsersDAO");
			User obj;
			
			List user = (ArrayList) userDAO.findByLoginname((credentials.getUsername()));
			logger.info("user Name " + user);
			if(user.isEmpty()==true){
				errors.rejectValue("username", "error.login.invalid-user",null, "Incorrect Username.");
				logger.info("Invalid user " + credentials.getUsername());
				request.setAttribute("invalidUser",getText("error.invalidUser"));
			}
			else
			{
				obj = (User) user.get(0);
				username = obj.getLoginname();
				logger.info("Validating user credentials for: "	+ credentials.getUsername());

				if (credentials.getUsername().equals(username) == false) {
					request.setAttribute("invalidUser",getText("error.invalidUser"));
					errors.rejectValue("username", "error.login.invalid-user",
							null, "Incorrect Username.");
					
				} 
				else {
					userpwd = obj.getPassword();
					if (credentials.getPassword().equals(userpwd) == false) {
						request.setAttribute("invalidUser",getText("error.invalidUser"));
						errors.rejectValue("password", "error.login.invalid-pass",null, "Incorrect Password.");						
					} else {						
						request.getSession().setMaxInactiveInterval(this.getSessionTimeOut());	
						logger.info("Session Time out : "+request.getSession().getMaxInactiveInterval());	
						request.getSession().setAttribute("USERID", obj.getUserid());
						request.getSession().setAttribute("USERROLE", obj.getUserrole());	
					}
				}
			}		
		}
	}
	
}